<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告 -->
      <el-alert title="注意：只允许为第三级分类添加相关参数！" type="warning" :closable="false" show-icon></el-alert>

      <!-- 商品选择 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品的级联 -->
          <el-cascader
            v-model="selectedCateKdys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加参数</el-button>

          <!-- 动态参数表格渲染 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >{{ item }}</el-tag>

                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParmas(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加属性</el-button>

          <!-- 静态属性表格渲染 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >{{ item }}</el-tag>

                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParmas(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加参数表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { async } from "q";
export default {
  data() {
    return {
      //分类商品数据
      cateList: [],
      //级联选择框配置对象
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //级联选择框双向绑定的数组
      selectedCateKdys: [],
      //tab页签被激活的名称
      activeName: "many",
      //动态参数的数据
      manyTableData: [],
      //静态属性的数据
      onlyTableData: [],
      //控制添加对话框
      addDialogVisible: false,
      //添加参数的表单对象
      addForm: {},
      //添加参数表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      //控制编辑对话框
      editDialogVisible: false,
      //编辑表单对象
      editForm: {},
      //编辑表单对象的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    //获取所有商品分类数据
    this.getCateList();
  },
  methods: {
    //获取所有商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类数据失败");
      }

      this.cateList = res.data;
      console.log(this.cateList);
    },
    //级联选择框的值变化是触发
    handleChange() {
      this.getParamsData();
    },
    //tab 页签点击事件
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    //获取参数列表数据
    async getParamsData() {
      //只允许选择三级分类
      if (this.selectedCateKdys.length !== 3) {
        this.selectedCateKdys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }

      //选择了三级分类
      console.log(this.selectedCateKdys);
      //根据分类id，和当前模板，获取对应参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取分类参数失败");
      }

      // 将字符串拆分成数组（将res.data中的attr_vals处理后再覆盖原来的attr_vals）
      res.data.forEach(item => {
        // 若attr_vals中包含数据 则拆分 否则直接返回一个空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //控制本行文本框显示与隐藏
        item.inputVisible = false;
        //本行文本框输入的值
        item.inputValue = "";
      });
      console.log(res.data);

      //保存动态参数
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        //保存静态属性
        this.onlyTableData = res.data;
      }
    },
    //对话框关闭时触发
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //点击确定按钮，添加参数
    addParams() {
      //对表单进行验证
      this.$refs.addFormRef.validate(async valid => {
        //表单验证失败
        if (!valid) return;

        //验证通过
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );

        if (res.meta.status !== 201) {
          return this.$message.error("参数添加失败");
        }

        this.$message.success("参数添加成功");
        this.addDialogVisible = false;
        //刷新参数
        this.getParamsData();
      });
    },
    //点击修改按钮 显示对话框
    async showEditDialog(attr_id) {
      //查询当前参数的信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }

      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    //清空编辑表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //点击确定 修改参数
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;

        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("参数修改失败");
        }

        this.$message.success("参数修改成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    //根据id删除参数
    async removeParmas(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      //确定删除
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除参数失败");
      }

      this.$message.success("删除参数成功");
      this.getParamsData();
    },
    //文本框使其焦点或触发Enter键 触发
    async handleInputConfirm(row) {
      // 若输入空格或无效内容 则清除
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }

      //输入有效内容 则进行处理
      row.attr_vals.push(row.inputValue.trim()); //将数据添加到数组
      row.inputValue = "";
      row.inputVisible = false;

      //持久化数据
      this.saveAttrVals(row);
    },
    //将 操作后的 attr_vals 保存到数据库
    async saveAttrVals(row) {
      //持久化数据
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ") //拼接成字符串
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("修改参数项失败");
      }

      this.$message.success("修改参数项成功");
    },
    //点击按钮展示文本框
    showInput(row) {
      row.inputVisible = true;
      //让文本框自动获得焦点
      //$nextTick：当页面元素被重新渲染后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除对应的可选项tag
    handleClose(i, row) {
      //删除一项 splice会修改原数组
      row.attr_vals.splice(i, 1);
      //更新数据库
      this.saveAttrVals(row);
    }
  },
  //计算属性
  computed: {
    //返回true，则禁用按钮
    isBtnDisabled() {
      if (this.selectedCateKdys.length !== 3) {
        return true;
      }
      return false;
    },
    //当前选择的三级分类id
    cateId() {
      if (this.selectedCateKdys.length === 3) {
        return this.selectedCateKdys[2];
      }
      return null;
    },
    //动态计算标题的文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    }
  }
};
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
.input-new-tag {
  width: 120px;
}
</style>